import React from "react";
import { useNavigate } from "react-router-dom";
import { Button, Checkbox, Form, Input, message } from "antd";

import "./index.scss";
import { login } from "@/api/user";
import { useAppDispatch } from "@/hooks";
import { setUserInfo } from "@/stores/user";

/**
 * 表单校验失败
 */
const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

const Login: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  /**
   * 表单校验成功提交
   */
  const onFinish = async (values: any) => {
    // 调用接口
    const res = await login(values.username, values.password);

    // 判断业务状态码是否成功
    if (res.code === "200") {
      // 消息提示
      message.success("登录成功");
      // 将数据储存下来
      dispatch(setUserInfo(res.data));
      const url = res.data?.checkedkeys[0] || "/dashboard/console";
      // 跳转到首页
      navigate(url, { replace: true });
    } else {
      // 消息提示
      message.error(res.message);
    }
  };

  return (
    <div className="page-login">
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ username: "admin", password: "123456" }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
